import axios from 'axios'
const lui = window.lui;
// create an axios instance
const service = axios.create()
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    lui.loading()
    Object.assign(config.params || {}, {
      operation_type: '1111',
      version_id: '111',
      user_id: 306465
    })
    if(localStorage.token){
        config.params.token = localStorage.token
    }
    if(localStorage.userDetail && localStorage.userDetail != 'undefined'){
        config.params.user_id = JSON.parse(localStorage.userDetail).id
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    lui.loading('close')
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    lui.loading('close');
    // if the custom code is not 20000, it is judged as an error.
    if (res.result_code != 0 && !response.config.url.includes('educloud/api/openAPI')) {
      lui.toast({
        position: 'top',
        text: res.message || 'Error',
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    lui.loading('close')
    console.log('err' + error) // for debug
    lui.toast({
      position: 'top',
      text: error.message,
    })
    return Promise.reject(error)
  }
)

export default service
